package com.sphsine.bip;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.mapper.VatInvoiceItemsMapper;
import com.javaweb.admin.mapper.VatInvoiceMapper;
import com.javaweb.admin.service.*;
import com.javaweb.admin.vo.vatinvoice.VatInvoiceNcDTO;
import com.javaweb.admin.vo.vatinvoiceitems.VatInvoiceItemsListVo;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.DynamicDataSource;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.javaweb.common.utils.StringUtils;
import com.sphchina.esb.webservice.INCRequset;
import com.sphsine.bip.requestDTO.VatInvoiceParam;
import com.sphsine.bip.responseDTO.VatInvoiceDTO;
import com.sphsine.bip.responseDTO.VatInvoiceItemsDTO;
import com.sphsine.bip.responseDTO.VatInvoiceResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

import static com.javaweb.common.utils.DateUtils.YYYYMMDD;

@Service
@Slf4j
public class BIPServiceImpl implements IBIPService{

    @Autowired
    IAnnualBudgetService annualBudgetService;
    @Autowired
    IPriceVariNoticeService priceVariNoticeService;
    @Autowired
    IBipServiceLogService bipServiceLogService;
    @Autowired
    ICommercialAcquisitionReportService commercialAcquisitionReportService;
    @Autowired
    private IOrgCodeReferService orgCodeReferService;

    @Autowired
    private VatInvoiceMapper invoiceMapper;

    @Autowired
    private VatInvoiceItemsMapper invoiceItemsMapper;

    @Autowired
    private INCRequset ncRequset;

    @Autowired
    private IVatInvoiceService vatInvoiceService;

//    private static final Logger log = LoggerFactory.getLogger(BIPServiceImpl.class);

    @Override
    public JsonResult callEsb(String body, String ServiceId) {
        try {
            String url = SHYPConstants.PLANREPORT_URL_SUFFIX+"?access_token="+SHYPUtil.getToken(true);
            DDKJConfig config = new SHYPConfig();
            config.setUseSandbox(false);
            SHYPRequest request = null;
            request = new SHYPRequest(config);
            String postData = "{\n" +
                    "\t\"pageParam\": [\n" +
                    "\t\t{\n" +
                    "\t\t\t\"page\": 1,\n" +
                    "\t\t\t\"pageSize\": 10\n" +
                    "\t\t}\n" +
                    "\t],\n" +
                    "\t\"queryParams\": [\n" +
                    "\t\t{\n" +
                    "\t\t\t\"period\": \"xxx\",\n" +
                    "\t\t\t\"purchaseOrg\": \"1528\",\n" +
                    "\t\t\t\"saleOrg\": \"1173\",\n" +
                    "\t\t\t\"material\": \"X0119000001\",\n" +
                    "\t\t\t\"yearly\": \"2023\"\n" +
                    "\t\t}\n" +
                    "\t]\n" +
                    "}";
            String result = request.postData(url, "", null, "",false);
            return JsonResult.success(result);
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }

    }




    private boolean checkPurchaseCode(String orgCode)
    {
        return ("1528".equals(orgCode) || "1529".equals(orgCode) || "1173".equals(orgCode))?true:false;
    }

    @Override
    public JsonResult sendBudget(String body, Integer id) {
        try {
            if(StringUtils.isEmpty(body))
            {
                //根据id生成提交的body报文
                List<AnnualBudgetData> budgetList = new ArrayList<>(1);
                AnnualBudgetList postList = new AnnualBudgetList();
                AnnualBudget budget = annualBudgetService.GetDetail(id);
                if(budget==null)
                {
                    return JsonResult.error("未找到id:"+id.toString()+"的预算记录信息");
                }
                AnnualBudgetData data = new AnnualBudgetData();
                data.setYearly(budget.getYearly());
                String bipOrgCode = annualBudgetService.GetBIPOrgCode(budget.getPurchaseCode()==null?"":budget.getPurchaseCode());
                data.setFactoryOrg(budget.getSaleCode());
                data.setPurchaseOrg(StringUtils.isEmpty(bipOrgCode)?budget.getPurchaseCode():bipOrgCode);
                data.setMaterial(budget.getMaterialCode());
                data.setInternalPrice(budget.getInternalPrice()==null? BigDecimal.ZERO:budget.getInternalPrice());
                data.setPurchaseNum(budget.getPurchaseNum());
                data.setPurchaseAmount(budget.getPurchaseAmount());
                data.setPurchaseMargin(budget.getPurchaseMargin());
                data.setSalesUnitPrice(budget.getSalesUnitPrice()==null?BigDecimal.ZERO:budget.getSalesUnitPrice());
                data.setSaleNum(budget.getSaleNum());
                data.setSaleAmount(budget.getSaleAmount());
                data.setSaleMargin(budget.getSaleMargin());
                if(budget.getVariableCost()!=null) {
                    data.setVariableCost(budget.getVariableCost());
                }
                else
                {
                    data.setVariableCost(BigDecimal.ZERO);
                }
                data.setBudgetState("基准版".equals(budget.getClassification())?"0":"1");
                data.setImportMark("BS-"+DateUtils.getDate());
                budgetList.add(data);
                postList.setData(budgetList);
                body = JSON.toJSONString(postList, SerializerFeature.WriteBigDecimalAsPlain);
            }
            DDKJConfig config = new SHYPConfig();
            config.setUseSandbox(false);
            SHYPRequest request = null;
            request = new SHYPRequest(config);
            String url = SHYPConstants.BUDGET_URL_SUFFIX+"?access_token="+SHYPUtil.getToken(config.getUseSandbox());
            AnnualBudgetList budgetList = JSON.parseObject(body,AnnualBudgetList.class);
            BipServiceLog log = new BipServiceLog();
            if(!checkPurchaseCode(budgetList.getData().get(0).getFactoryOrg())) {
                BigDecimal num = budgetList.getData().get(0).getPurchaseNum();
                BigDecimal amount = budgetList.getData().get(0).getPurchaseAmount();
                BigDecimal margin = budgetList.getData().get(0).getPurchaseMargin();
                num = num.add(amount).add(margin);
                if(num.compareTo(BigDecimal.ZERO)!=0) {
                    String info = request.postData(url, "", null, body, config.getUseSandbox());
                    JSONObject result = JSON.parseObject(info);
                    log.setSubmitNo(id.toString() + "_" + budgetList.getData().get(0).getMaterial());
                    log.setBid(id);
                    log.setRequestBody(body);
                    log.setSubmitTime(DateUtils.now());
                    log.setResponseBody(info);
                    log.setResponseCode(result.getString("code"));
                    log.setResponseResult(result.getString("message"));
                    bipServiceLogService.save(log);
                    if (result.getString("code").equals("200")) {
                        annualBudgetService.UpdateZT(id, "N");
                        return JsonResult.success(result);
                    } else {
                        return JsonResult.error(info);
                    }
                }else
                {
                    String info = "采购数量、采购金额及采购边际均为0，不提交接口";
                    log.setSubmitNo(id.toString() + "_" + budgetList.getData().get(0).getMaterial());
                    log.setBid(id);
                    log.setRequestBody(body);
                    log.setSubmitTime(DateUtils.now());
                    log.setResponseBody(info);
                    log.setResponseCode("");
                    log.setResponseResult("");
                    bipServiceLogService.save(log);
                    annualBudgetService.UpdateMark(id);
                    return JsonResult.error(info);

                }
            }
            else
            {
                String info = "sale_code未启用或org_code_refer表中未匹配到bip_org_code";
                log.setSubmitNo(id.toString() + "_" + budgetList.getData().get(0).getMaterial());
                log.setBid(id);
                log.setRequestBody(body);
                log.setSubmitTime(DateUtils.now());
                log.setResponseBody(info);
                log.setResponseCode("");
                log.setResponseResult("");
                bipServiceLogService.save(log);
                annualBudgetService.UpdateMark(id);
                return JsonResult.error(info);
            }

        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }

    }

    @Override
    public JsonResult sendNotice(String body, Integer id) {
        try {
            DDKJConfig config = new SHYPConfig();
            config.setUseSandbox(false);
            SHYPRequest request = null;
            request = new SHYPRequest(config);
            String url = SHYPConstants.PRICENOTICE_URL_SUFFIX+"?access_token="+SHYPUtil.getToken(config.getUseSandbox());
            if(StringUtils.isEmpty(body))
            {
                //根据id生成提交的body报文
                List<PriceVariNoticeData> noticeList = new ArrayList<>(1);
                PriceVariNoticeList postList = new PriceVariNoticeList();
                PriceVariNotice notice = priceVariNoticeService.GetDetail(id);
                if(notice==null)
                {
                    return JsonResult.error("未找到id:"+id.toString()+"的结算价记录信息");
                }
                PriceVariNoticeData data = new PriceVariNoticeData();
                data.setYearly(notice.getYearly());
                data.setPeriod(notice.getPeriod());
                data.setSaleOrg(notice.getSaleCode());
                data.setPurchaseOrg(notice.getPurchaseCode());
                data.setMaterial(notice.getMaterialCode());
                data.setAssertPrice(notice.getAssertPrice()==null? BigDecimal.ZERO:notice.getAssertPrice());
                noticeList.add(data);
                postList.setData(noticeList);
                body = JSON.toJSONString(postList, SerializerFeature.WriteBigDecimalAsPlain);
            }
//            String postData = "{\n" +
//                    "\t\"data\": [\n" +
//                    "\t\t{\n" +
//                    "\t\t\t\"purchaseOrg\": \"1173\",\n" +
//                    "\t\t\t\"saleOrg\": \"1184\",\n" +
//                    "\t\t\t\"material\": \"0121130203\",\n" +
//                    "\t\t\t\"assertPrice\": \"234.00\",\n" +
//                    "\t\t\t\"period\": \"10\",\n" +
//                    "\t\t\t\"yearly\": \"2023\"\n" +
//                    "\t\t}\n" +
//                    "\t]\n" +
//                    "}";
            String info = request.postData(url, "", null, body,config.getUseSandbox());
            JSONObject result = JSON.parseObject(info);
            BipServiceLog log = new BipServiceLog();
            AnnualBudgetList budgetList = JSON.parseObject(body,AnnualBudgetList.class);
            log.setSubmitNo(id.toString()+"_"+budgetList.getData().get(0).getMaterial());
            log.setBid(id);
            log.setRequestBody(body);
            log.setSubmitTime(DateUtils.now());
            log.setResponseBody(info);
            log.setResponseCode(result.getString("code"));
            log.setResponseResult(result.getString("message"));
            bipServiceLogService.save(log);
            if(result.getString("code").equals("200"))
            {
                annualBudgetService.UpdateZT(id,"N");
                return JsonResult.success(result);
            }
            else
            {
                return JsonResult.error(info);
            }
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }

    }

    @Override
    public JsonResult getPlanReport(String body) {
        try {
            String url = SHYPConstants.PLANREPORT_URL_SUFFIX+"?access_token="+SHYPUtil.getToken(false);
            DDKJConfig config = new SHYPConfig();
            config.setUseSandbox(false);

            SHYPRequest request = null;
            request = new SHYPRequest(config);
            if(StringUtils.isEmpty(body))
            {
                //根据id生成提交的body报文
                StringBuilder sb = new StringBuilder();
                sb.append("{\n" +
                        "\t\"pageParam\": \n" +
                        "\t\t{\n" +
                        "\t\t\t\"page\": 1,\n" +
                        "\t\t\t\"pageSize\": 10\n" +
                        "\t\t}\n" +
                        "\t,\n" +
                        "\t\"queryParams\": \n" +
                        "\t\t{\n" +
                        "\t\t\t\"yearly\": \""+ DateUtil.year(DateUtil.date()) +"\"\n" +
                        "\t\t}\n" +
                        "\t\n" +
                        "}"+
                        "}"
                );
                body = sb.toString();
            }
//            String postData = "{\n" +
//                    "\t\"data\": [\n" +
//                    "\t\t{\n" +
//                    "\t\t\t\"purchaseOrg\": \"1173\",\n" +
//                    "\t\t\t\"saleOrg\": \"1184\",\n" +
//                    "\t\t\t\"material\": \"0121130203\",\n" +
//                    "\t\t\t\"assertPrice\": \"234.00\",\n" +
//                    "\t\t\t\"period\": \"10\",\n" +
//                    "\t\t\t\"yearly\": \"2023\"\n" +
//                    "\t\t}\n" +
//                    "\t]\n" +
//                    "}";
            String info = request.postData(url, "", null, body,false);
            PlanReportResult reportResult = JSON.parseObject(info,PlanReportResult.class);
            JSONObject result = JSON.parseObject(info);
            BipServiceLog log = new BipServiceLog();
            //AnnualBudgetList budgetList = JSON.parseObject(body,AnnualBudgetList.class);
            log.setSubmitNo("");
            log.setBid(0);
            log.setRequestBody(body);
            log.setSubmitTime(DateUtils.now());
            log.setResponseBody(info);
            log.setResponseCode(result.getString("code"));
            log.setResponseResult(result.getString("message"));
            bipServiceLogService.save(log);
            if(result.getString("code").equals("200"))
            {
                PageInfoData data= reportResult.getData();
                List<PlanReportData> dataList= data.getPageInfo().getData();
                for (PlanReportData item:dataList) {
                    CommercialAcquisitionReport entity = new CommercialAcquisitionReport();
                    entity.setYearly(item.getYearly());
                    entity.setPurchaseAmount(item.getPurchaseAmount());
                    entity.setPurchaseCode(item.getPurchaseOrgCode());
                    entity.setSaleCode(item.getFactoryOrgCode());
                    entity.setFinePurchaseCode(annualBudgetService.GetFineOrgCode(item.getPurchaseOrgCode()));
                    entity.setFineSaleCode(annualBudgetService.GetFineOrgCode(item.getFactoryOrgCode()));
                    entity.setMaterialCode(item.getMaterialCode());
                    entity.setPurchaseNum(item.getPurchaseQuantity());
                    entity.setMonthly(item.getMonthly());
                    entity.setPurchaseMargin(item.getPurchaseMargin());
                    entity.setBipId(item.getId());
                    entity.setDataSource("bip_online");
                    entity.setTwoVoteNum(item.getTwoVoteNum());
                    entity.setTwoVoteMoney(item.getTwoVoteMoney());
                    entity.setNotTwoVoteNum(item.getNotTwoVoteNum());
                    entity.setNotTwoVoteMoney(item.getNotTwoVoteMoney());

                    commercialAcquisitionReportService.edit(entity);
                }
                //annualBudgetService.UpdateZT(id,"N");
                //return JsonResult.success(result);
                return JsonResult.success(result);
            }
            else
            {
                return JsonResult.error(info);
            }
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }
    }

    @Override
    public JsonResult manualSyncReport(String yearly, String monthly) {
        try {
            String url = SHYPConstants.PLANREPORT_URL_SUFFIX+"?access_token="+SHYPUtil.getToken(false);
            DDKJConfig config = new SHYPConfig();
            config.setUseSandbox(false);
            SHYPRequest request = null;
            request = new SHYPRequest(config);
            String body = "";
            if(StringUtils.isEmpty(body))
            {
                //根据id生成提交的body报文
                StringBuilder sb = new StringBuilder();
                sb.append("{\n" +
                        "\t\"pageParam\": \n" +
                        "\t\t{\n" +
                        "\t\t\t\"page\": 1,\n" +
                        "\t\t\t\"pageSize\": 10000\n" +
                        "\t\t}\n" +
                        "\t,\n" +
                        "\t\"queryParams\": \n" +
                        "\t\t{\n");
                if(!StringUtils.isEmpty(monthly)) {
                    sb.append("\t\t\t\"yearly\": \""+ yearly +"\",\n");
                    sb.append("\t\t\t\"period\": \"" + monthly + "\"\n");
                }
                else
                {
                    sb.append("\t\t\t\"yearly\": \""+ yearly +"\"\n");
                }
                sb.append("\t\t}\n" +
                        "\t\n" +
                        "}"
                );
                body = sb.toString();
            }
            String info = request.postData(url, "", null, body,false);
            PlanReportResult reportResult = JSON.parseObject(info,PlanReportResult.class);
            JSONObject result = JSON.parseObject(info);
            BipServiceLog log = new BipServiceLog();
            //AnnualBudgetList budgetList = JSON.parseObject(body,AnnualBudgetList.class);
            log.setSubmitNo("");
            log.setBid(0);
            log.setRequestBody(body);
            log.setSubmitTime(DateUtils.now());
            log.setResponseBody(info);
            log.setResponseCode(result.getString("code"));
            log.setResponseResult(result.getString("message"));
            bipServiceLogService.save(log);
            if(result.getString("code").equals("200"))
            {
                //删除原有年度和月度的收购报表数据
                commercialAcquisitionReportService.removeReportData(yearly,monthly);

                PageInfoData data= reportResult.getData();
                List<PlanReportData> dataList= data.getPageInfo().getData();
                for (PlanReportData item:dataList) {
                    CommercialAcquisitionReport entity = new CommercialAcquisitionReport();
                    entity.setYearly(item.getYearly());
                    entity.setPurchaseAmount(item.getPurchaseAmount());
                    entity.setPurchaseCode(item.getPurchaseOrgCode());
                    entity.setSaleCode(item.getFactoryOrgCode());
                    entity.setFinePurchaseCode(annualBudgetService.GetFineOrgCode(item.getPurchaseOrgCode()));
                    entity.setFineSaleCode(annualBudgetService.GetFineOrgCode(item.getFactoryOrgCode()));
                    entity.setMaterialCode(item.getMaterialCode());
                    entity.setPurchaseNum(item.getPurchaseQuantity());
                    entity.setMonthly(item.getMonthly());
                    entity.setPurchaseMargin(item.getPurchaseMargin());
                    entity.setBipId(item.getId());
                    entity.setDataSource("bip_online");
                    entity.setTwoVoteNum(item.getTwoVoteNum());
                    entity.setTwoVoteMoney(item.getTwoVoteMoney());
                    entity.setNotTwoVoteNum(item.getNotTwoVoteNum());
                    entity.setNotTwoVoteMoney(item.getNotTwoVoteMoney());

                    commercialAcquisitionReportService.edit(entity);
                }
                //annualBudgetService.UpdateZT(id,"N");
                //return JsonResult.success(result);
                return JsonResult.success("手工同步收购报表数据成功");
            }
            else
            {
                return JsonResult.error(info);
            }
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult syncVatInvoice(String orgCode) {
        try {
            Integer pageNum = 1;
            Integer pageSize = 500;
            String url = SHYPConstants.BIP_VAT_BILL + "?access_token=" + SHYPUtil.getToken(false);
            DDKJConfig config = new SHYPConfig();
            config.setUseSandbox(false);
            SHYPRequest request = null;
            request = new SHYPRequest(config);
            VatInvoiceParam vatInvoiceParam = new VatInvoiceParam();
            String billDateEnd = DateUtils.getDate();
            String billDateBegin = DateUtils.dateTime(DateUtils.addDays(new Date(), -90));
            VatInvoiceParam.VatInvoiceSearch searchParam = vatInvoiceParam.new VatInvoiceSearch(orgCode, billDateBegin, billDateEnd);
            vatInvoiceParam.setPagenum(pageNum);
            vatInvoiceParam.setPagesize(pageSize);
            vatInvoiceParam.setSearchParam(searchParam);
            String body = JSONObject.toJSONString(vatInvoiceParam);
            String response = request.postData(url, "", null, body, false);
            VatInvoiceResponse vatInvoiceResponse = JSONObject.parseObject(response, VatInvoiceResponse.class);
            Integer totalCount = vatInvoiceResponse.getData().getTotalEntity().getTotalCount();
            log.error("start handle " + orgCode);
            while (pageNum <= totalCount / pageSize + 1) {
                handle(orgCode, url, request, vatInvoiceParam);
                vatInvoiceParam.setPagenum(++pageNum);
            }
            log.error("end handle " + orgCode);
        } catch (Exception e) {
            log.error("handle error" + orgCode);
            log.error(e.getMessage());
        }
        try {
            log.error("start submitVatInvoiceToNC " + orgCode);
            submitVatInvoiceToNC();
            log.error("end submitVatInvoiceToNC " + orgCode);
        } catch (Exception e) {
            log.error("submitVatInvoiceToNC error" + orgCode);
            log.error(e.getMessage());
            return JsonResult.error(e.getMessage());
        }
        return JsonResult.success();
    }

    @Override
    public void submitVatInvoiceToNC() {
        try {
            String endKqrq = DateUtils.dateTimeNow(YYYYMMDD);
            String startKqrq = DateUtils.parseDateToStr(YYYYMMDD,DateUtils.addDays(new Date(), -90));
            List<VatInvoice> list = vatInvoiceService.getByKqrq(startKqrq,endKqrq);
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            List<VatInvoiceNcDTO> dtos = new ArrayList<>();
            for (VatInvoice vatInvoice : list) {
                VatInvoiceNcDTO dto = new VatInvoiceNcDTO();
                dtos.add(dto);
                dto.setOrgcode(vatInvoice.getOrgCode());
                dto.setVbillcode(vatInvoice.getFpHm());
                String supplierName = StringUtils.isNotEmpty(vatInvoice.getXsfYhzh())&&(vatInvoice.getXsfYhzh().contains("021900319410301")||vatInvoice.getXsfYhzh().contains("05508305263100035")) ? vatInvoice.getXsfMc()+".":vatInvoice.getXsfMc();
                dto.setSuppliername(supplierName);
                dto.setNtotalorigmny(vatInvoice.getJshj());
                dto.setNtax(vatInvoice.getHjse());
                dto.setFpdm(vatInvoice.getFpDm());
                dto.setKprq(StringUtils.isNotEmpty(vatInvoice.getKprq())?DateUtils.dateTime(DateUtil.parse(vatInvoice.getKprq())):"");
                dto.setFj(vatInvoice.getFilePath());
                dto.setRemark(vatInvoice.getBz());
                dto.setKhh(vatInvoice.getXsfYhzh());
                String dataSource = DynamicDataSource.getDataSource();
                List<VatInvoiceItems> items = invoiceItemsMapper.selectList(new QueryWrapper<VatInvoiceItems>().eq("pk_invoice",vatInvoice.getOutId()));
                if (!CollectionUtils.isEmpty(items)) {
                    Set<String> set = new HashSet<>();
                    for (VatInvoiceItems item : items) {
                        set.add(item.getXmmc());
                    }
                    dto.setPjmx(String.join(";", set));
                }
                vatInvoice.setMark(vatInvoice.getMark() + 1);
            }
            String body = JSON.toJSONString(dtos);
            JsonResult jsonResult = ncRequset.callToNC(body, "/uapws/service/SWYToNCInvoice");
            DynamicDataSource.setDataSource("bip");
            vatInvoiceService.updateBatchById(list,500);
        } catch (Exception e) {
            log.error("submitVatInvoiceToNC error aaaa");
            log.error("submitVatInvoiceToNC error " + e.getStackTrace().toString());
            log.error(e.getMessage());
        }
    }

    private void handle(String orgCode, String url, SHYPRequest request, VatInvoiceParam vatInvoiceParam) throws Exception {
        String body = JSONObject.toJSONString(vatInvoiceParam);
        String response = request.postData(url, "", null, body, false);
        VatInvoiceResponse vatInvoiceResponse = JSONObject.parseObject(response, VatInvoiceResponse.class);
        List<VatInvoiceDTO> bills = vatInvoiceResponse.getData().getBills();
        if (CollectionUtils.isEmpty(bills)) {
            return;
        }
        for (VatInvoiceDTO bill : bills) {
            VatInvoice vatInvoice = new VatInvoice();
            BeanUtils.copyProperties(bill, vatInvoice, "id");
            vatInvoice.setOutId(bill.getId());
            vatInvoice.setOrgCode(orgCode);
            VatInvoice one = invoiceMapper.selectOne(new QueryWrapper<VatInvoice>().eq("out_id", vatInvoice.getOutId()));
            if (one != null) {
                continue;
            }
            List<VatInvoiceItemsDTO> items = JSONObject.parseArray(bill.getItems(), VatInvoiceItemsDTO.class);
            vatInvoice.setItems(null);
            invoiceMapper.insert(vatInvoice);
            if (!CollectionUtils.isEmpty(items)) {
                for (VatInvoiceItemsDTO item : items) {
                    VatInvoiceItems vatInvoiceItems = new VatInvoiceItems();
                    BeanUtils.copyProperties(item, vatInvoiceItems);
//                    VatInvoiceItems vatItem = invoiceItemsMapper.selectOne(new QueryWrapper<VatInvoiceItems>().eq("pk_invoice_detail", item.getPkInvoiceDetail()).eq("pk_invoice", item.getPkInvoice()));
                    VatInvoiceItems vatItem = invoiceItemsMapper.getBy(item.getPkInvoiceDetail(), item.getPkInvoice());
                    if (vatItem == null) {
                        invoiceItemsMapper.insert(vatInvoiceItems);
                    }
                }
            }
        }
    }

}
